//
//  CZTextView.swift
//  weibo
//
//  Created by Apple on 16/3/18.
//  Copyright © 2016年 KY. All rights reserved.
//

import UIKit

@IBDesignable
class CZTextView: UITextView {

    // MARK:    懒加载控件
    private lazy var placeholderLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFontOfSize(13)
        label.textColor = UIColor.lightGrayColor()
        label.numberOfLines = 0
        return label
    }()
    
    //  重写font属性
    override var font: UIFont? {
        didSet {
            placeholderLabel.font = font
        }
    }
    
    override var text: String? {
        didSet {
            placeholderLabel.hidden = hasText()
        }
    }
    
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        setupUI()
        //  使用通知监听文字改变
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textChange", name: UITextViewTextDidChangeNotification, object: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupUI()
        //  使用通知监听文字改变
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textChange", name: UITextViewTextDidChangeNotification, object: nil)
    }

    private func setupUI() {
        
        addSubview(placeholderLabel)
        
        //  添加约束
        placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
        //  添加约束
        //  LessThanOrEqual 意思是如果文本的宽度小于约束的宽度则使用自己的宽度约束
        //  GreaterThanOrEqual 意思是如果文本的宽度大于约束的宽度则使用自己的宽度约束，否则使用约束的宽度
        addConstraint(NSLayoutConstraint(item: placeholderLabel, attribute: NSLayoutAttribute.Width, relatedBy: .LessThanOrEqual, toItem: self, attribute: .Width, multiplier: 1, constant: -10))
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        //  设置坐标
        placeholderLabel.x = 5
        placeholderLabel.y = 8

    }
    
    @IBInspectable
    var placeholder: String? {
        didSet {
            placeholderLabel.text = placeholder
            placeholderLabel.sizeToFit()
        }
    }
    // MARK:    监听文字改变的方法
    
    @objc private func textChange() {
//        if hasText() {
//            placeholderLabel.hidden = true
//        } else {
//            placeholderLabel.hidden = false
//        }
        print("textchange")
        placeholderLabel.hidden = hasText()
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
}
